<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Spa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Log;
use Carbon\Carbon;
use App\Services\OssService;
use OSS\OssClient;
use Auth;

class SpaController extends Controller
{
    //单页列表
    public function lst()
    {
        $spa = DB::table('single_page')->orderBy('id','desc')->paginate(PAGE_NUM);
        //列表筛选
        if(isset($_GET['id_search']) || isset($_GET['sku_search']) || isset($_GET['country_search'])){
            $where = [];
            $id = trim($_GET['id_search']);
            $sku = trim($_GET['sku_search']);
            $country = trim($_GET['country_search']);
            $status = trim($_GET['status_search']);
            if($_GET['id_search']){
                $where[] = ['id','like',"$id%"];
            }
            if($_GET['sku_search']){
                $where[] = ['good_sku','like',"$sku%"];
            }
            if($_GET['country_search']){
                $where[] = ['country','like',"%$country%"];
            }
            if($_GET['status_search'] !== ''){
                $where[] = ['status','=',"$status"];
            }
            $spa = DB::table('single_page')
                        ->where($where)
                        ->orderBy('id','desc')
                        ->paginate(PAGE_NUM);
        //   $url=url('admin/spa/lst');
        //   $adminusers->withPath($url.'?id_search='.$id.'&sku_search='.$sku.'&country_search='.$country);
        }
        return view('admin.spa.lst',compact('spa','id','sku','country','status'));
    }

    //创建单页
    public function create()
    {
        $country = $this->country(); //国家
        $template = $this->template(); //模板
        return view('admin.spa.create',compact('country','template'));
    }

    //编辑
    public function edit($id)
    {
        $data = Spa::findOrFail($id);
        $country = $this->country(); //国家
        $template = $this->template(); //模板
        $imgs = $data->original_imgs;
        $imgs = trim($imgs,';');
        $imgs = explode(';',$imgs);
        $image = trim($data->image,';');
        $image = explode(';',$image);
        return view('admin.spa.edit',compact('data','country','template','imgs','image'));
    }

    //创建保存
    public function store(Request $request)
    {
        //参数验证
        $this->validate($request, [
            'pro_name'      => 'required',
            'good_name'     => 'required',
            'good_sku'      => 'required',
            'sale_num'      => 'required',
            'amount'        => 'required',
            'end_time'      => 'required',
            'raw_price'     => 'required'
        ],['required'=>':attribute 必填'],['pro_name'=>'单页名称','good_name'=>'商品名称','good_sku'=>'商品sku','sale_num'=>'已售数量','amount'=>'总件数','end_time'=>'结束时间','raw_price'=>'原价']);
        $post = $request->input();
        $admin_id = Auth::guard('admin')->id();
        $key = 'spa:img:'.$admin_id.':path';
        $url = '';
        if(app('redis')->EXISTS($key)){
            $image = app('redis')->SMEMBERS($key);
            $image = implode(';',$image);
            app('redis')->DEL($key);
        }
        $detail = isset($post['editor']) ? $post['editor'] : '';
        $created_at = date('Y-m-d H:i:s');
        //保存表单数据
        $spa = Spa::create([
            'pro_name'      => $post['pro_name'],
            'model'         => $post['model'],
            'country'       => $post['country'],
            'good'          => $post['good'],
            'good_name'     => $post['good_name'],
            'good_sku'      => $post['good_sku'],
            'original_imgs' => $post['original_img'],
            'image'         => isset($image) ? $image : '',
            'raw_price'     => $post['raw_price'],
            // 'current_price' => $post['current_price'],
            'sale_num'      => $post['sale_num'],
            'amount'        => $post['amount'],
            'end_time'      => $post['end_time'],
            'url'           => $url,
            'status'        => $post['status'],
            'detail'        => $detail,
            'created_at'    => $created_at
        ]);
        $id = $spa->id;
        $spa->url = 'product/view/id/'.$id;
        $spa->save();
        if($spa){
            //修改 maxnina下的 special_price
            // $map = $this->getCountryCurrencyMap();
            // $this->updateMaxninaPrice($post['good_sku'],$post['current_price'],$map[$post['country']]);
            exit(json_encode(array('code'=>1, 'url'=>'/admin/spa/lst')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>'系统错误')));
        }
    }

    //修改
    public function update(Request $request)
    {
        //参数验证
        $this->validate($request, [
            'pro_name'      => 'required',
            'good_name'     => 'required',
            'sale_num'      => 'required',
            'amount'        => 'required',
            'end_time'      => 'required|digits_between:1,2',
            'raw_price'     => 'required',
        ],['required'=>':attribute 必填'],['pro_name'=>'单页名称','good_name'=>'商品名称','good_sku'=>'商品sku','sale_num'=>'已售数量','amount'=>'总件数','end_time'=>'结束时间','raw_price'=>'原价']);

        $post = $request->input();
        $spa = Spa::find($post['id']);
        $old_image = $spa->image;
        $image = $old_image;
        $admin_id = Auth::guard('admin')->id();
        $key = 'spa:img:'.$admin_id.':path';
        if(app('redis')->EXISTS($key)){
            $new_image = app('redis')->SMEMBERS($key);
            $new_image = implode(';',$new_image);
            app('redis')->DEL($key);
            $image = $old_image.$new_image.';';
        }

        //保存表单数据
        $spa->pro_name      = $post['pro_name'];
        $spa->model         = $post['model'];
        $spa->good_name     = $post['good_name'];
        $spa->image         = $image;
        $spa->raw_price     = $post['raw_price'];
        // $spa->current_price = $post['current_price'];
        $spa->sale_num      = $post['sale_num'];
        $spa->amount        = $post['amount'];
        $spa->end_time      = $post['end_time'];
        $spa->status        = $post['status'];
        $spa->detail        = $post['editor'] ? $post['editor'] : $spa->detail;
        $z = $spa->save();
        if($z){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/spa/lst')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>'系统错误')));
        }
    }

    //上传图片到 Oss
    public function upload(Request $request)
    {
        $oss = new OssService();
        $pix = env('IMG_PIX');
        $fix = '?x-oss-process=image/resize,m_pad,h_600,w_600';
        if(isset( $_FILES['file'])){
            $file = $_FILES['file'];
            //临时文件路径
            $tempPath = $file['tmp_name'];
            //组装要上传的到oss的路径
            $ossPath = 'spa/';
            $ext = explode('.',$file['name']);
            $saveFilename = md5(microtime()).'.'.$ext[1];
            $ossPath = $ossPath.$saveFilename;
            $res = $oss->ossUpload($ossPath,$tempPath);
            $res = json_decode($res,true);
            $admin_id = Auth::guard('admin')->id();
            if($res['code']==1){
                app('redis')->SADD('spa:img:'.$admin_id.':path',$pix.$ossPath.$fix);
                echo 'ok';
            }else{
                echo 'error';
            }
        }else{
            //在富文本编辑器上传图片走下面逻辑
            foreach($_FILES as $v){
                $file = $v;
            }
            //临时文件路径
            $tempPath = $file['tmp_name'];
            //组装要上传的到 oss的路径
            $ossPath = 'spa/';
            $ext = explode('.',$file['name']);
            $saveFilename = md5(microtime()).'.'.$ext[1];
            $ossPath = $ossPath.$saveFilename;
            $res = $oss->ossUpload($ossPath,$tempPath);
            $res = json_decode($res,true);
            if($res['code']==1){
                return json_encode(["errno"=>0,"data"=>[$pix.$ossPath]]);
            }
        }
    }

    
    //获取商品信息
    public function getGoodsData(Request $request)
    {
        $sku = $request->get('sku');
        $country = $request->get('country');
        $map = $this->getCountryCurrencyMap();
        $currency = $map[$country];
        $lanmap = $this->lanMap();
        $lan = $lanmap[$country];
        $url = env('API_URL').'services/product/view/product_id/'.$sku;
        $headers = array(
            'User-Currency:'.$currency,
            'User-Country:'.$country,
            'User-Lan:'.$lan,
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',
        );
        $data = $this->curl_request_with_header($url,'get','',$headers);
        echo $data;
    }

    //删除图片 >>>未使用
    public function deleteImage(Request $request){
        $id = $request->get('id');
        $img = $request->get('img'); //原图
        $image = $request->get('image'); //上传图片
        $spa = Spa::find($id);
        if($image){
            $images = $spa->image;
            $images = str_replace($image.';','',$images);
            $spa->image = $images;
        }
        if($img){
            $imgs = $spa->original_imgs;
            $imgs = str_replace($img.';','',$imgs);
            $spa->original_imgs = $imgs;
        }
        $z = $spa->save();
        if($z){
            // $oss = new OssService();
            // $res = $oss->ossDelete($ossPath);
            exit(json_encode(array('code'=>1, 'url'=>'/admin/spa/'.$id.'/edit')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>'图片删除失败,请联系管理员')));
        }
    }

    //清除单页缓存
    public function clearCache($id){
        $spaModel = Spa::findOrFail($id);
        $country = $spaModel->country;
        $key =  'spa:product:'.$country.':'.$id;
        $z = app('redis')->del($key);
        if($z){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/spa/lst')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>'找不到可清除缓存')));
        }
    } 

    //调用maxnina接口 >修改maxnina商品的特殊价格 >>>未使用
    private function updateMaxninaPrice($product_id,$special_price,$currency)
    {
        $url = env('API_URL').'v32/product/updateSpecialPrice?product_id='.$product_id.'&special_price='.$special_price.'&currency='.$currency;
        $this->curl_request_without_header($url,'get');
    }

    //带 header头的 curl请求函数
    private function curl_request_with_header($url,$type="post",$data="",$headers)
    {
      $ch = curl_init();
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
      curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
      curl_setopt($ch,CURLOPT_HEADER,0);
      curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
      
      $type = strtolower($type);
      switch($type){
          case 'get':
          break;
          case 'post':
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
          break;
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    
    //不带 header头的 curl请求函数
    private function curl_request_without_header($url,$type="post",$data="")
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch,CURLOPT_HEADER,0);
        
        $type = strtolower($type);
        switch($type){
        case 'get':
        break;
        case 'post':
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    
    //国家缩写映射
    private function country(){
        $arr = [
            'SA'=>'沙特',
            // 'AE'=>'阿联酋',
            // 'QA'=>'卡塔尔',
            // 'KW'=>'科威特',
            // 'BH'=>'巴林',
            // 'OM'=>'阿曼',
            // 'EG'=>'埃及',
            // 'US'=>'美国',
            'TH'=>'泰国',
            // 'MY'=>'马来西亚',
            // 'ID'=>'印尼',
            // 'IN'=>'印度',
            // 'TW'=>'台湾省'
        ];
        return $arr;
    }

    //模板映射
    private function template(){
        $arr = [
            '1'=>'默认',
        ];
        return $arr;
    }

    //货币映射 >>>未使用
    private function getCountryCurrencyMap()
    {
        $map = [
            'BH' => 'BHD',  // Bahraini Dinar
            'KW' => 'KWD',  // Kuwaiti Dinar
            'OM' => 'OMR',  // Omani Rial
            'QA' => 'QAR',  // Qatari Rial
            'SA' => 'SAR',  // Saudi Riyal
            'AE' => 'AED',  // United Arab Emirates Dirham
            'US' => 'USD',  // US Dollar
            'GB' => 'GBP',  // 英国  British Pound Sterling
            'AU' => 'AUD',  // | Australian Dollar
            'PL' => 'PLN',  // 波兰  Poland  |  Polish Zloty
            'RU' => 'RUB',  // 俄罗斯  Russia  |  Russian Ruble
            'DK' => 'DKK',  // 丹麦  Denmark  |  Danish Krone
            'JP' => 'JPY',  //  |  Japanese Yen
            'SG' => 'SGD',  // 新加坡  Singapore  |  Singapore Dollar
            'NZ' => 'NZD',  // 新西兰  New Zealand  |  New Zealand Dollar
            'IN' => 'INR',  //  |  Indian Rupee
            'EG' => 'EGP',  //  |  Egyptian Pound
            'DE' => 'EUR',  // 德国  Germany  |  Euro
            'FR' => 'EUR',  // 法国  France
            'ES' => 'EUR',  // 西班牙  Spain
            'IT' => 'EUR',  // 意大利  Italy
            'EE' => 'EUR',  // 爱沙尼亚  Estonia  |  Estonian Kroon
            'CY' => 'EUR',  // 塞浦路斯  Cyprus
            'BY' => 'BYR',  // 白俄罗斯  Belarus  |  Belarusian Ruble
            'IE' => 'EUR',  // 爱尔兰  Ireland
            'NL' => 'EUR',  // 荷兰  Netherlands
            'CH' => 'CHF',  // 瑞士  Switzerland  |  Swiss Franc
            'SE' => 'SEK',  // 瑞典  Sweden  |  Swedish Krona
            'TH' => 'THB',  // 泰国  | 泰铢
        ];

        return $map;
    }

    //语言关系映射
    private function lanMap(){
        $arr = [
            'SA'=>'ar',
            'AE'=>'ar',
            'QA'=>'en',
            'KW'=>'en',
            'BH'=>'en',
            'OM'=>'en',
            'EG'=>'en',
            'US'=>'en',
            'TH'=>'en',
            'MY'=>'en',
            'ID'=>'en',
            'IN'=>'en',
            'TW'=>'en'
        ];
        return $arr;
    }
}